<?php
// Key
// Alex McClung
// November, 2007
// Represents a key on a keyboard. Has accessors to set and retrieve a list of neiboring keys.
// 
// This software is freely distributable under the terms of the GNU General Public License (Version 3).
// For details, see the author's web site: http://www.mcclungalexander.com/
class Key
{

	//===================================================================================
	// Private Variables
	
	//===================================================================================
	// Public Variables
	public $value;			//<! Key value
	public $shift_value;	//<! Key value (when the SHIFT key is held down)
	public $neighbors;		//<! Array of Key objects
	
	//===================================================================================
	// Public Functions

	//-----------------------------------------------------------------------------------
	// Class constructor
	// $v (char) Key value
	// $n (array) Array of Key objects that represents this key's neighbors
	public function __construct($v, $n=NULL)
	{
		// Save the face value
		$this->value = $v;
		
		// Determine the "shift" value (the key's value when the SHIFT key is held down)
		$asc_val = (is_numeric($v)) ? $this->FindNumericShiftValue($v) : ord($v) - 32;
		$this->shift_value = chr($asc_val);
		
		// Did they pass in an array of neighboring keys?
		if($n != NULL)
			$this->neighbors = $n;
		else
			$this->neighbors = array();
	}
	
	//-----------------------------------------------------------------------------------
	// Adds a neighboring key to the list
	// $k Key object instance
	public function AddNeighbor($k)
	{
		$this->neighbors[] = $k;
	}
	
	//-----------------------------------------------------------------------------------
	// Gets a random neighboring Key object
	// Returns: Key object instance
	public function GetRandomNeighbor()
	{
		$i = rand(0, count($this->neighbors)-1);
		return $this->neighbors[$i];
	}
	
	//===================================================================================
	// Private Functions
	
	//-----------------------------------------------------------------------------------
	// Determines the value of a key character when the Shift button is pressed.
	// Returns: char
	private function FindNumericShiftValue($v)
	{
		$shift = "!@#$%^&*()";
		$index = ($v > 0) ? $v-1 : 9;
		return ord(substr($shift,$index,1));
	}
}

?>